use clap::{Parser, Subcommand};

use crate::create_polygon::create_polygons;
use crate::image_convert::convert_images;
use crate::image_pack::pack_images;
use crate::image_tile_pack::pack_tile_images;

#[derive(Parser, Debug)]
#[clap(
    version = "1.0",
    author = "entropy",
)]
pub struct App {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    #[clap(
        about = "Converts images of a specific format in a given directory"
    )]
    ImgConv {
        #[clap(help = "The source directory path", index = 1)]
        path: String,
        #[clap(help = "The source image format (e.g. jpg)", index = 2)]
        source_format: String,
        #[clap(help = "The target image format (e.g. png)", index = 3)]
        target_format: String,
    },
    #[clap(
        about = "Pack images"
    )]
    ImgPack {
        #[clap(help = "The source directory path", index = 1)]
        path: String,
        #[clap(help = "The source image name pattern", index = 2)]
        source_name_pattern: String,
        #[clap(help = "The target image name", index = 3)]
        output_name: Option<String>,
    },
    ImgTilePack {
        #[clap(help = "The source directory path", index = 1)]
        path: String,
        #[clap(help = "The source image name pattern", index = 2)]
        source_name_pattern: String,
        #[clap(help = "The target image name", index = 3)]
        output_name: Option<String>,
    },
    #[clap(
        about = "Convert image pack rect info to polygons"
    )]
    CreatePolygon {
        #[clap(help = "The rect info file path", index = 1)]
        path: String,
        #[clap(help = "The texture id", index = 2)]
        texture_id: String,
    },
}

impl Commands {
    pub fn run(&self) {
        match self {
            Commands::ImgConv { path, source_format, target_format } => {
                convert_images(path, &source_format, &target_format).unwrap();
            }
            Commands::ImgPack { path, source_name_pattern, output_name } => {
                let output = String::from("output.png");
                let output = output_name.as_ref().unwrap_or(&output);
                pack_images(path, &source_name_pattern, output).unwrap();
            }
            Commands::ImgTilePack { path, source_name_pattern, output_name } => {
                let output = String::from("output.png");
                let output = output_name.as_ref().unwrap_or(&output);
                pack_tile_images(path, &source_name_pattern, output).unwrap();
            }
            Commands::CreatePolygon { path, texture_id } => {
                create_polygons(path, texture_id).unwrap();
            }
        }
    }
}

